<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed!');

class Users extends OC_Controller {

	function __construct()
	{
		parent::__construct();
		$this->load->model('users/user_model');
	}

	function _remap($method, $params = array())
	{
		parent::_remap($method, $params);

		if (method_exists($this, $method))
			return call_user_func_array(array($this, $method), $params);
		else
			show_404();
	}

	function init_header()
	{
		$this->header['jeasyui'] = TRUE;
		$this->header['source_bot'] = array(
			script_tag(site_url('users/themescript/app/users.js'))
		);
	}

	function index()
	{
		$this->init_header();
		$this->header['nav'] = 'configuration';
		$this->header['pagetitle'] = 'Manage User';
		$this->header['roles']  = $this->bitauth->get_roles();
		$this->header['groups'] = $this->user_model->get_groups()->rows;
		$this->view('users/user_view');
	}

	function load_users()
	{
		$params = $this->input->post();
		$result = $this->user_model->get_users($params);
		print(json_encode($result));
	}

	function save_user()
	{
		$post = $this->input->post();

		if ( ! empty($post['pass1']))
			$post['password'] = $post['pass1'];

		unset($post['pass1']);
		unset($post['pass2']);
			

		if (empty($post['user_id']))
		{
			$result = $this->bitauth->add_user($post);

			if ($post['active'] == '1' && $result && $result->activation_code) 
				$this->bitauth->activate($result->activation_code);
		}
		else
		{
			$result = $this->bitauth->update_user($post['user_id'], $post);
		}

		print(json_encode(array(
			'success' => TRUE
		)));
	}

	function delete_user()
	{
		$user_id = $this->input->post('user_id');
		$result  = $this->user_model->delete_user($user_id);
		print(json_encode(array('success' => $result)));
	}

	function load_groups()
	{
		$params = $this->input->post();
		$result = $this->user_model->get_groups($params);
		print(json_encode($result));
	}

	function save_group()
	{
		$post = $this->input->post();
		$post['roles'] = array($post['roles']);

		if (empty($post['group_id']))
		{
			unset($post['group_id']);
			$this->bitauth->add_group($post);
		}
		else
			$this->bitauth->update_group($post['group_id'], $post);

		print(json_encode(array('success' => TRUE)));
	}

	function delete_group()
	{
		$group_id = $this->input->post('group_id');
		$result   = $this->bitauth->delete_group($group_id);
		print(json_encode(array('success' => $result)));
	}

	function load_assoc()
	{
		$params = $this->input->post();
		$result = $this->user_model->get_assoc($params);
		print(json_encode($result));
	}

	function save_assoc()
	{
		$this->bitauth->update_user(
			$this->input->post('user_id'), 
			array(
				'groups' => array($this->input->post('group_id'))
			)
		);

		print(json_encode(array('success' => TRUE)));
	}

}